<template>
  <div class="doctor-department">
    <!-- 页面标题 -->
    <el-page-header content="医生科室" sub-title="查看所有科室信息" />
    
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="searchKey" placeholder="搜索科室名称" @keyup.enter="fetchData">
            <template #append>
              <el-button @click="fetchData">搜索</el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-select v-model="levelFilter" placeholder="筛选层级" @change="fetchData">
            <el-option label="全部" value="" />
            <el-option label="一级科室" value="1" />
            <el-option label="二级科室" value="2" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="refreshData">
            <el-icon><Refresh /></el-icon>刷新数据
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据请求加载中提示 -->
    <el-skeleton v-if="loading" :loading="loading" animated count="3" />
    
    <!-- 数据展示表格 -->
    <el-table
      v-else
      :data="departmentList"
      border
      stripe
      highlight-current-row
      style="width: 100%; margin-top: 20px;"
      @row-click="handleRowClick"
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="department_id" label="科室ID" align="center" width="100" />
      <el-table-column 
        prop="department_name" 
        label="科室名称" 
        align="center"
        :formatter="highlightSearchText"
      />
      <el-table-column prop="level" label="层级" align="center" width="80" />
      <el-table-column prop="parent_id" label="父级ID" align="center" width="100" />
      <el-table-column 
        prop="create_time" 
        label="创建时间" 
        align="center"
        width="180"
        :formatter="formatCreateTime" 
      />
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="mini"
            @click="viewDepartment(scope.row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态提示 -->
    <el-empty v-if="!loading && departmentList.length === 0" description="暂无科室数据" />
    
    <!-- 分页组件 -->
    <el-pagination
      v-if="total > 0"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; text-align: right;"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { Refresh } from '@element-plus/icons-vue';

// 状态管理
const loading = ref(false);
const departmentList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchKey = ref('');
const levelFilter = ref('');
const uniqueIds = ref(new Set()); // 用于存储已存在的科室ID

// 格式化日期
const formatCreateTime = (row) => {
  if (!row.create_time) return '';
  const date = new Date(row.create_time);
  return date.toLocaleString();
};

// 高亮搜索文本
const highlightSearchText = (row, column) => {
  if (!searchKey.value) return row[column.property];
  const regex = new RegExp(searchKey.value, 'gi');
  return row[column.property].replace(regex, match => 
    `<span style="color: #f56c6c;">${match}</span>`
  );
};

// 去重逻辑：基于科室ID判断唯一性
const filterDuplicates = (data) => {
  const uniqueData = [];
  data.forEach(item => {
    if (!uniqueIds.value.has(item.department_id)) {
      uniqueIds.value.add(item.department_id);
      uniqueData.push(item);
    }
  });
  return uniqueData;
};

// 获取科室数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await axios.get(
      'http://localhost:8080/hospital5/department/findAll',
      {
        params: {
          page: currentPage.value,
          pageSize: pageSize.value,
          keyword: searchKey.value,
          level: levelFilter.value
        }
      }
    );
    
    // 清空已存在的ID集合（用于新的查询）
    if (currentPage.value === 1) {
      uniqueIds.value.clear();
    }
    
    // 过滤重复数据
    const uniqueData = filterDuplicates(response.data);
    
    // 如果是第一页，直接替换；否则追加
    if (currentPage.value === 1) {
      departmentList.value = uniqueData;
    } else {
      departmentList.value = [...departmentList.value, ...uniqueData];
    }
    
    // 更新总数（假设接口返回total字段）
    total.value = response.data.total || departmentList.value.length;
    
  } catch (error) {
    console.error('获取科室数据失败:', error);
    ElMessage.error('获取科室数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const refreshData = () => {
  currentPage.value = 1;
  fetchData();
};

// 分页事件处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchData();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchData();
};

// 查看科室详情
const handleRowClick = (row) => {
  viewDepartment(row);
};

const viewDepartment = (row) => {
  // 这里可以跳转到科室详情页或显示详情弹窗
  ElMessage.info(`查看科室: ${row.department_name}`);
  // 实际项目中可以这样实现：
  // router.push({ name: 'DepartmentDetail', params: { id: row.department_id } });
};

// 初始化加载数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.doctor-department {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.filter-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

/* 自定义表格样式 */
.el-table {
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.el-table th {
  background-color: #f2f3f5;
  color: #606266;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

.el-pagination {
  margin-top: 20px;
}
</style>